#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <string>
#include <cstring>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "Log.hpp"
#include "Inetaddr.hpp"

using namespace std;

enum 
{
    SOCK_ERROR = 1,
    BIND_ERROR,
    LISTEN_ERROR,
    USAGE_ERROR,
};

const static int defaultsockfd = -1;
const static int gbacklog = 16;

class TcpServer
{
public:
    TcpServer(uint16_t port) :_port(port), _listensock(defaultsockfd), _isrunning(false)
    {}

    void InitServer()
    {
        //创建流式套接字
        _listensock = ::socket(AF_INET, SOCK_STREAM, 0);
        if(_listensock < 0)
        {
            LOG(FATAL, "socket error");
            exit(SOCK_ERROR);
        }
        LOG(DEBUG, "socket create success, sockfd is: %d\n", _listensock);

        // bind
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        int n = ::bind(_listensock, (struct sockaddr*)&local, sizeof(local));
        if(n < 0)
        {
            LOG(FATAL, "bind error");
            exit(BIND_ERROR);
        }
        LOG(DEBUG, "bind success, sockfd is: %d\n", _listensock);

        // tcp是面向连接的，所以通信之前，先建立连接。 服务器是被连接的
        // tcpserver启动，未来要一直等待客户
        n = ::listen(_listensock, gbacklog);
        if(n < 0)
        {
            LOG(FATAL, "listen error");
            exit(LISTEN_ERROR);
        }
    }

    void Server(int sockfd, InetAddr client)
    {
        LOG(DEBUG, "get a new link, info %s:%d\n", client.Ip().c_str(), client.Port());
        string clientaddr = "[" + client.Ip() + ":" + to_string(client.Port()) + "]# ";
        while(true)
        {
            char inbuffer[1024];
            ssize_t n = read(sockfd, inbuffer, sizeof(inbuffer)-1);
            if(n > 0)
            {
                inbuffer[n] = 0;
                cout << clientaddr << inbuffer << endl;
                string echo_string = "[server echo]# ";
                echo_string += inbuffer;

                write(sockfd, echo_string.c_str(), echo_string.size());
            }
            else if(n == 0)
            {
                //client 退出&&关闭连接
                LOG(INFO, "%s quit\n", clientaddr.c_str());
                break;
            }
            else
            {
                LOG(ERROR, "read error\n", clientaddr.c_str());
                break;
            }
        }
        ::close(sockfd);
    }   
    void Loop()
    {
        _isrunning = true;
        // 不能直接获取数据，先获取连接
        while(_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = ::accept(_listensock, (struct sockaddr*)&peer, &len);
            if(sockfd < 0)
            {
                LOG(WARNING, "accept error\n");
                continue;
            }

            Server(sockfd, InetAddr(peer));
        }
        _isrunning = false;
    }


    ~TcpServer()
    {
        if(_listensock > defaultsockfd)
        {
            ::close(_listensock);
        }
    }

private:
    uint16_t _port;
    int _listensock;
    bool _isrunning;
};